package com.example.stock.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.stock.entity.dao.AmountVolDao;
import com.example.stock.entity.dao.ProBarStockDao;
import com.example.stock.entity.eo.AmountVolEo;
import com.example.stock.entity.eo.ProBarStockEo;
import com.example.stock.service.IServiceAmountVol;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ServiceAmountVolImpl implements IServiceAmountVol {

    @Resource
    private ProBarStockDao proBarStockDao;
    @Resource
    private AmountVolDao amountVolDao;

    @Override
    public void generateAmountVol() {

        List<String> stringList = proBarStockDao.listAllTsCode();
        for (String tsCode : stringList) {
            List<ProBarStockEo> list = proBarStockDao.list(Wrappers.<ProBarStockEo>lambdaQuery().eq(ProBarStockEo::getTsCode, tsCode));

            Map<LocalDateTime, List<ProBarStockEo>> localDateTimeListMap = list.stream().collect(Collectors.groupingBy(t->t.getTradeTime().withDayOfMonth(15).withHour(0).withMinute(0).withSecond(0)));
            List<AmountVolEo> amountVolEos = new ArrayList<>();
            for (Map.Entry<LocalDateTime, List<ProBarStockEo>> entry : localDateTimeListMap.entrySet()) {
                AmountVolEo amountVolEo = new AmountVolEo();
                amountVolEo.setTsCode(tsCode);
                List<ProBarStockEo> value = entry.getValue();
                amountVolEo.setAmount(value.stream().mapToDouble(ProBarStockEo::getAmount).sum());
                amountVolEo.setVol(value.stream().mapToDouble(ProBarStockEo::getVol).sum());
                amountVolEo.setAsset("STOCK");
                amountVolEo.setTradeTime(entry.getKey());
                amountVolEo.setDuration("1MOUTH");
//                amountVolDao.save(amountVolEo);
                amountVolEos.add(amountVolEo);

            }
            if (CollectionUtil.isNotEmpty(amountVolEos)) {
                amountVolDao.saveBatch(amountVolEos, 100);
            }
        }

    }

    @Override
    public List<String> listTopTen(LocalDateTime time) {
        LocalDateTime localDateTime = time.plusMonths(-1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        return amountVolDao.listTopTen(localDateTime);
    }
}
